import { createBrowserRouter, useLocation, Navigate } from "react-router-dom";
import Dlogin from "@/pages/Dlogin";
import DoctorLayout from "@/pages/DoctorLayout";
import LocalMain from "@/pages/LocalMain";
import NotFound from "@/pages/NotFound";
import ErrorPage from "@/pages/ErrorPage";
import useUserStore from "@/store/user";

function RequireAuth({ children }) {
  const isAuthenticated = useUserStore((state) => state.isAuthenticated);
  let location = useLocation();
  if (!isAuthenticated) {
    return <Navigate to="/" state={{ from: location }} replace />;
  }
  return children;
}

const routes = createBrowserRouter([
  {
    path: "/",
    element: <Dlogin />,
    errorElement: <ErrorPage />,
  },
  {
    path: "/home",
    element: (
      <RequireAuth>
        <DoctorLayout />
      </RequireAuth>
    ),
    children: [
      {
        index: true, //默认子路由
        element: <LocalMain />,
      },
    ],
  },
  {
    path: "/notfound",
    element: <NotFound />,
  },
]);
export default routes;
